package tw.edu.tku.im.maze;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


public class StartGameRepParser extends PacketParser {
   public static StartGameRepParser INSTANCE = new StartGameRepParser();
   
   private StartGameRepParser() { }
   
   private static Member[] parseMembers(JSONArray jsonArray) throws JSONException {
      if(jsonArray==null){ return null; }
      Member[] ans = new Member[jsonArray.length()];
      for(int i=0; i<jsonArray.length(); i++) {
         if(jsonArray.isNull(i)) { break; }
         ans[i] = Member.parse(jsonArray.getJSONObject(i));
      }
      return ans;
   }

   @Override
   public StartGameRep parse(JSONObject jsonObj) throws JSONException {
      JSONObject result = jsonObj.getJSONObject("result");
      
      JSONArray jsonTeam1 = result.getJSONArray("team1");
      Member[] teamOneMember = StartGameRepParser.parseMembers(jsonTeam1);
      MazeMap map = MazeMap.parse(result.getJSONObject("map"));
      if(result.isNull("team2")) {
         return new StartGameRep(teamOneMember, map);
      }
      else {
         JSONArray jsonTeam2 = result.getJSONArray("team2");
         Member[] teamTwoMember = StartGameRepParser.parseMembers(jsonTeam2);
         return new StartGameRep(teamOneMember, teamTwoMember, map);
      }
   }

   @Override
   public String acceptName() {
      return "startGameResponse";
   }

}
